(() => {
    function $(id) { return document.getElementById(id); }
    const out = $('out');
    function show(obj) {
        out.textContent = typeof obj === 'string' ? obj : JSON.stringify(obj, null, 2);
    }
    async function getJson(path) {
        const res = await fetch(path, { cache: 'no-store' });
        const ct = res.headers.get('content-type') || '';
        if (ct.includes('application/json')) return await res.json();
        return await res.text();
    }
    async function postJson(path, body) {
        const res = await fetch(path, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body || {}),
        });
        const ct = res.headers.get('content-type') || '';
        if (ct.includes('application/json')) return await res.json();
        return await res.text();
    }
    
    async function onRun() {
        show('正在启动点击任务...');
        try {
            const data = await getJson('/click');
            show(data);
        } catch (e) {
            show(String(e));
        }
    }
    
    // PM2重启功能
    async function onRestart() {
        show('正在重启PM2进程...');
        try {
            const data = await postJson('/pm2-restart', {});
            if (data.ok) {
                let output = `✅ ${data.message}\n\n`;
                
                if (data.restartOutput) {
                    output += `重启输出:\n${data.restartOutput}\n\n`;
                }
                
                if (data.logOutput) {
                    output += `最新日志:\n${data.logOutput}`;
                }
                
                if (data.logError) {
                    output += `\n日志错误: ${data.logError}`;
                }
                
                show(output);
            } else {
                show('重启PM2进程失败: ' + (data.message || '未知错误'));
            }
        } catch (e) {
            show('重启PM2进程失败: ' + String(e));
        }
    }
    
    // 点位设置
    async function openPoints() {
        const modal = document.getElementById('points-modal');
        const list = document.getElementById('points-list');
        modal.style.display = 'flex';
        list.innerHTML = '加载中...';
        try {
            const data = await getJson('/click-points');
            const items = (data && data.items) || [];
            list.innerHTML = '';
            if (!items.length) {
                list.textContent = '暂无点位';
                return;
            }
            for (const it of items) {
                const row = document.createElement('div');
                row.style.display = 'flex';
                row.style.alignItems = 'center';
                row.style.justifyContent = 'space-between';
                row.style.gap = '12px';
                row.style.border = '1px solid #eee';
                row.style.borderRadius = '6px';
                row.style.padding = '8px 10px';
                row.innerHTML = `<div>#${it.index + 1}  (x:${it.x}, y:${it.y})</div>
                    <div>
                        <label style=\"margin-right:8px;\">
                            <input type=\"radio\" name=\"mode-${it.index}\" value=\"1\" ${it.mode === 1 ? 'checked' : ''}/> 单击
                        </label>
                        <label>
                            <input type=\"radio\" name=\"mode-${it.index}\" value=\"2\" ${it.mode === 2 ? 'checked' : ''}/> 双击
                        </label>
                    </div>`;
                list.appendChild(row);
            }
        } catch (e) {
            list.textContent = '加载失败';
        }
    }
    
    function closePoints() {
        const modal = document.getElementById('points-modal');
        modal.style.display = 'none';
    }
    
    async function savePoints() {
        const list = document.getElementById('points-list');
        const rows = Array.from(list.querySelectorAll('div'));
        const updates = [];
        for (let i = 0; i < rows.length; i++) {
            const idx = i;
            const selected = list.querySelector(`input[name="mode-${idx}"]:checked`);
            if (!selected) continue;
            updates.push({ index: idx, mode: parseInt(selected.value, 10) === 2 ? 2 : 1 });
        }
        if (!updates.length) { closePoints(); return; }
        const res = await postJson('/click-points', { items: updates });
        show(res);
        closePoints();
    }
    
    // 去除编辑/保存逻辑
    window.addEventListener('DOMContentLoaded', async () => {
        document.getElementById('btn-points').addEventListener('click', openPoints);
        $('btn-run').addEventListener('click', onRun);
        document.getElementById('btn-restart').addEventListener('click', onRestart);
        document.getElementById('points-close').addEventListener('click', closePoints);
        document.getElementById('points-save').addEventListener('click', savePoints);
    });
})();


